package org.ilc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author malongbo
 */
public class Bootstrap {
    private static Log log = LogFactory.getLog ("Bootstrap");
    private static Context context = null;

    /**
     * 启动程序
     * @param dir Server根目录
     */
    public static void start(String dir){

        if (context != null && context.getAcceptor () != null && context.getAcceptor ().isActive ()) {
            if(log.isWarnEnabled()){
                log.warn("server already startup ");
            }
            return;
        }
        try {
            context = new Context ();
            // 初始化context
            context.contextInitialize(dir);

            // 启动socket 消息接收器
            context.getAcceptor().start();

            //启动任务队列执行器
            context.getTaskQueue ().start ();

            context.getMessageQueue().start();
        } catch (Exception e) {
            log.error (e);
        }

    }

    public static void shutDown(){
        if (null != context) {
            if (null != context.getMessageQueue ())
                context.getMessageQueue().stop();
            if (null != context.getTaskQueue ())
                context.getTaskQueue ().stop ();
            if (null != context.getAcceptor ())
                context.getAcceptor().stop();
            if (null != context)
                context.destroy();
        }
    }
    public static Context getContext() {
        if (null == context) {
            throw new NullPointerException ("Context is null");
        }
        return context;
    }
}
